#include "reportwidget.h"
#include "ui_reportwidget.h"
#include "srsettingsdialog.h"
#include "imagelabel.h"
#include "../../DicomViewer/DicomViewer/Global/commondefs.h"

#include <QPrintPreviewDialog>
#include <QPrintDialog>
#include <QPrinter>
#include <QPainter>
#include <QSettings>
#include <QCloseEvent>
#include <QDesktopWidget>
#include <QDesktopServices>
#include <QScreen>
#include <QFileDialog>
#include <QDateTime>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QFile>
#include <QTextStream>
#include <QDebug>

ReportWidget::ReportWidget(QWidget *parent) :
    m_status(0),
    QWidget(parent),
    ui(new Ui::ReportWidget)
{
    ui->setupUi(this);
    setAcceptDrops(true);
    initLogicalDpi();
    reflushReportFormat();

    QSettings s;
    ui->reportPhyCombo->addItems(s.value(REPORT_PHY_LIST).toStringList());
    //ui->verifyPhyCombo->addItems(s.value(VERIFY_PHY_LIST).toStringList());
}

ReportWidget::~ReportWidget()
{
    delete ui;
}

void ReportWidget::setupConnections(bool conn)
{
    if (conn) {
        connect(ui->bodyPartCombo, SIGNAL(currentTextChanged(QString)), this, SIGNAL(reportModified()));
        connect(ui->studyMethodEdit, SIGNAL(textChanged(QString)), this, SIGNAL(reportModified()));
        connect(ui->findingsEdit, SIGNAL(textChanged()), this, SIGNAL(reportModified()));
        connect(ui->diagnoseEdit, SIGNAL(textChanged()), this, SIGNAL(reportModified()));
        connect(ui->reportPhyCombo, SIGNAL(currentTextChanged(QString)), this, SIGNAL(reportModified()));
        connect(ui->reportTimeEdit, SIGNAL(textChanged(QString)), this, SIGNAL(reportModified()));
        //connect(ui->verifyPhyCombo, SIGNAL(currentTextChanged(QString)), this, SIGNAL(reportModified()));
        connect(ui->verifyTimeEdit, SIGNAL(textChanged(QString)), this, SIGNAL(reportModified()));
    } else {
        disconnect(ui->bodyPartCombo, SIGNAL(currentTextChanged(QString)), this, SIGNAL(reportModified()));
        disconnect(ui->studyMethodEdit, SIGNAL(textChanged(QString)), this, SIGNAL(reportModified()));
        disconnect(ui->findingsEdit, SIGNAL(textChanged()), this, SIGNAL(reportModified()));
        disconnect(ui->diagnoseEdit, SIGNAL(textChanged()), this, SIGNAL(reportModified()));
        disconnect(ui->reportPhyCombo, SIGNAL(currentTextChanged(QString)), this, SIGNAL(reportModified()));
        disconnect(ui->reportTimeEdit, SIGNAL(textChanged(QString)), this, SIGNAL(reportModified()));
        //disconnect(ui->verifyPhyCombo, SIGNAL(currentTextChanged(QString)), this, SIGNAL(reportModified()));
        disconnect(ui->verifyTimeEdit, SIGNAL(textChanged(QString)), this, SIGNAL(reportModified()));
    }
}

void ReportWidget::openReportFile(const QString &json)
{
    QFile f(json);
    if (f.open(QIODevice::ReadOnly)) {
        QTextStream in(&f);
        QString json = in.readAll();
        if (!json.isEmpty()) {
            openReport(json.toUtf8());
        }
    } else {
        qDebug() << f.errorString();
    }
}

void ReportWidget::clearImages()
{
    foreach (ImageLabel *l, imgLabels) {
        l->deleteLater();
    }
    imgLabels.clear();
}

void ReportWidget::openReport(const QByteArray &json)
{
    clearImages();
    QJsonObject rjson = QJsonDocument::fromJson(json).object();
    report = json;
    QJsonObject req;
    req["StudyUid"] = rjson["StudyUid"].toString();
    setReadOnly(false);
    switch (m_status) {
    case 2:
    case 3:
        req["status"] = 31;
        m_status = 31;
        emit postReport(QJsonDocument(req).toJson(QJsonDocument::Compact));
        break;
    case 4:
        req["status"] = 41;
        m_status = 41;
        emit postReport(QJsonDocument(req).toJson(QJsonDocument::Compact));
        break;
    default:
        setReadOnly(true);
        break;
    }

    setupConnections(false);
    ui->patientIdEdit->setText(rjson["PatientId"].toString());
    ui->patientNameEdit->setText(rjson["PatientName"].toString());
    ui->patientSexEdit->setText(rjson["PatientSex"].toString());
    ui->patientAgeEdit->setText(rjson["PatientAge"].toString());
    ui->accNumEdit->setText(rjson["AccessionNumber"].toString());
    ui->studyTimeEdit->setText(rjson["StudyTime"].toString());
    ui->bodyPartCombo->setCurrentText(rjson["BodyPart"].toString());
    ui->findingsEdit->setText(rjson["Findings"].toString());
    ui->diagnoseEdit->setText(rjson["Diagnosis"].toString());
    ui->reportPhyCombo->setCurrentText(rjson["ReportPhysician"].toString());
    ui->reportTimeEdit->setText(rjson["ReportTime"].toString());
    //ui->verifyPhyCombo->setCurrentText(rjson["VerifyPhysician"].toString());
    ui->verifyTimeEdit->setText(rjson["VerifyTime"].toString());
    QJsonArray arr = rjson["Images"].toArray();
    QStringList imgs;
    for (int i = 0; i < arr.size(); ++i) {
        imgs += "report/" + arr.at(i).toString();
    }
    emit downloadImages(imgs);
    emit reportCompleted(rjson["Completed"].toBool());
    bool verify = rjson["Verified"].toBool();
    emit reportVerified(verify);
    ui->verifySignLabel->setVisible(verify);
    setupConnections(true);
}

void ReportWidget::reflushReportFormat()
{
    QSettings settings;
    QFont font;
    ui->institutionEdit->setText(settings.value(INSTITUTION_NAME_TEXT).toString());
    if (font.fromString(settings.value(INSTITUTION_NAME_FONT).toString())) {
        ui->institutionEdit->setFont(font);
    } else {
        font = ui->institutionEdit->font();
        settings.setValue(INSTITUTION_NAME_FONT, font.toString());
    }
    if (font.fromString(settings.value(REPORT_TITLE_FONT).toString())) {
        ui->reportTitleEdit->setFont(font);
    } else {
        font = ui->reportTitleEdit->font();
        settings.setValue(REPORT_TITLE_FONT, font.toString());
    }

    ui->reportTitleEdit->setText(settings.value(REPORT_TITLE_TEXT).toString());
    if (font.fromString(settings.value(PATIENT_INFO_FONT).toString())) {
        ui->patientIdLabel->setFont(font);
        ui->patientIdEdit->setFont(font);
        ui->patientNameLabel->setFont(font);
        ui->patientNameEdit->setFont(font);
        ui->patientSexLabel->setFont(font);
        ui->patientSexEdit->setFont(font);
        ui->patientAgeLabel->setFont(font);
        ui->patientAgeEdit->setFont(font);
        ui->accNumLabel->setFont(font);
        ui->accNumEdit->setFont(font);
        ui->studyTimeLabel->setFont(font);
        ui->studyTimeEdit->setFont(font);
        ui->bodyPartLabel->setFont(font);
        ui->bodyPartCombo->setFont(font);
        ui->studyMethodLabel->setFont(font);
        ui->studyMethodEdit->setFont(font);
    } else {
        font = ui->patientIdEdit->font();
        settings.setValue(PATIENT_INFO_FONT, font.toString());
    }
    if (font.fromString(settings.value(REPORT_TEXT_FONT).toString())) {
        ui->findingsLabel->setFont(font);
        ui->findingsEdit->setFont(font);
        ui->diagnoseLabel->setFont(font);
        ui->diagnoseEdit->setFont(font);
    } else {
        font = ui->findingsEdit->font();
        settings.setValue(REPORT_TEXT_FONT, font.toString());
    }
    if (font.fromString(settings.value(PHYSICIAN_INFO_FONT).toString())) {
        ui->reportPhyLabel->setFont(font);
        ui->reportPhyCombo->setFont(font);
        ui->verifyPhyLabel->setFont(font);
        //ui->verifyPhyCombo->setFont(font);
        ui->reportTimeLabel->setFont(font);
        ui->reportTimeEdit->setFont(font);
        ui->verifyTimeLabel->setFont(font);
        ui->verifyTimeEdit->setFont(font);
    } else {
        font = ui->reportPhyCombo->font();
        settings.setValue(PHYSICIAN_INFO_FONT, font.toString());
    }
    if (font.fromString(settings.value(FOOTNOTE_FONT).toString())) {
        ui->footNoteEdit->setFont(font);
    } else {
        font = ui->footNoteEdit->font();
        settings.setValue(FOOTNOTE_FONT, font.toString());
    }
    if (settings.value(FOOTNOTE_TEXT).toString().isEmpty()) {
        settings.setValue(FOOTNOTE_TEXT, tr("Reference Only, Valid on physician's signature."));
    }
    ui->footNoteEdit->setText(settings.value(FOOTNOTE_TEXT).toString());

    if (settings.value(IMAGE_WIDTH).toInt() <= 0) {
        settings.setValue(IMAGE_WIDTH, 50.0);
    }
    if (settings.value(IMAGE_HEIGHT).toInt() <= 0) {
        settings.setValue(IMAGE_HEIGHT, 50.0);
    }

    QSize imgSize = QSize(settings.value(IMAGE_WIDTH).toDouble()*xLogicalDpi/INCH_MM_RATIO,
                           settings.value(IMAGE_HEIGHT).toDouble()*yLogicalDpi/INCH_MM_RATIO);
    foreach (ImageLabel *l, imgLabels) {
        l->setImageSize(imgSize);
    }
}

void ReportWidget::initLogicalDpi()
{
    QDesktopWidget *desktop = QApplication::desktop();
    QList<QScreen*> screenList = QApplication::screens();
    QScreen *screen = screenList.at(desktop->screenNumber(this));
    xLogicalDpi = screen->logicalDotsPerInchX();
    yLogicalDpi = screen->logicalDotsPerInchY();
}

void ReportWidget::setReadOnly(bool yes)
{
    //ui->institutionEdit->setReadOnly(yes);
    ui->findingsEdit->setReadOnly(yes);
    ui->diagnoseEdit->setReadOnly(yes);
    ui->bodyPartCombo->setEnabled(!yes);
    ui->studyMethodEdit->setReadOnly(yes);
    ui->reportPhyCombo->setEnabled(!yes);
    //ui->verifyPhyCombo->setEnabled(!yes);
}

void ReportWidget::setStatus(int status)
{
    QJsonObject json = QJsonDocument::fromJson(report).object();
    QString suid = json["StudyUid"].toString();
    QJsonObject req;
    req["StudyUid"] = suid;
    switch (m_status) {
    case 31:
        req["status"] = 3;
        emit postReport(QJsonDocument(req).toJson(QJsonDocument::Compact));
        break;
    case 41:
        req["status"] = 4;
        emit postReport(QJsonDocument(req).toJson(QJsonDocument::Compact));
        break;
    }
    m_status = status;
}

void ReportWidget::setPaper(const QString &paper)
{
    QSize size;
    if (paper == "A5") {
        size.setWidth((148/INCH_MM_RATIO)*xLogicalDpi);
        size.setHeight((210/INCH_MM_RATIO)*yLogicalDpi);
    } else if (paper == "A3") {
        size.setWidth((297/INCH_MM_RATIO)*xLogicalDpi);
        size.setHeight((420/INCH_MM_RATIO)*yLogicalDpi);
    } else if (paper == "B4") {
        size.setWidth((250/INCH_MM_RATIO)*xLogicalDpi);
        size.setHeight((353/INCH_MM_RATIO)*yLogicalDpi);
    } else if (paper == "B5") {
        size.setWidth(6.93*xLogicalDpi);
        size.setHeight(9.84*yLogicalDpi);
    } else if (paper == "Customize") {
        size.setWidth(8.26*xLogicalDpi);
        size.setHeight(11.69*yLogicalDpi);
    } else {
        size.setWidth(8.26*xLogicalDpi);
        size.setHeight(11.69*yLogicalDpi);
    }
    resize(size);
}

bool ReportWidget::saveReport()
{
    QSettings s;
    QString phy = ui->reportPhyCombo->currentText();
    QStringList phys = s.value(REPORT_PHY_LIST).toStringList();
    phys.removeOne(phy);
    phys.prepend(phy);
    s.setValue(REPORT_PHY_LIST, phys);
    /*
    phy = ui->verifyPhyCombo->currentText();
    phys = s.value(VERIFY_PHY_LIST).toStringList();
    phys.removeOne(phy);
    phys.prepend(phy);
    s.setValue(VERIFY_PHY_LIST, phys);
    */

    QJsonObject json = QJsonDocument::fromJson(report).object();
    if (!ui->bodyPartCombo->currentText().isEmpty())
        json["BodyPart"] = ui->bodyPartCombo->currentText();
    if (!ui->studyMethodEdit->text().isEmpty())
        json["Method"] = ui->studyMethodEdit->text();
    if (!ui->findingsEdit->toPlainText().isEmpty())
        json["Findings"] = ui->findingsEdit->toPlainText();
    if (!ui->diagnoseEdit->toPlainText().isEmpty())
        json["Diagnosis"] = ui->diagnoseEdit->toPlainText();
    if (!ui->reportPhyCombo->currentText().isEmpty())
        json["ReportPhysician"] = ui->reportPhyCombo->currentText();
    json["ReportTime"] = ui->reportTimeEdit->text();
    //if (!ui->verifyPhyCombo->currentText().isEmpty())
        //json["VerifyPhysician"] = ui->verifyPhyCombo->currentText();
    json["VerifyTime"] = ui->verifyTimeEdit->text();

    QJsonArray arr;
    for (int i = 0; i < imgLabels.size(); ++i) {
        QString png = imgLabels.at(i)->getFileName();
        arr += png;
        imgLabels.at(i)->pixmap().save(cacheDir+"/"+png);
    }
    json["Images"] = arr;
    report = QJsonDocument(json).toJson(QJsonDocument::Compact);
    QFile f(cacheDir + "/" + json["StudyUid"].toString() + ".json");
    if (f.open(QIODevice::WriteOnly)) {
        QTextStream out(&f);
        out << report;
        f.close();

        QStringList fs;
        QJsonArray arr = json["Images"].toArray();
        for (int i = 0; i < arr.size(); ++i) {
            fs += arr[i].toString();
        }
        QString pdf = json["ReportPdf"].toString();
        if (json["Verified"].toBool() && (!pdf.isEmpty())) fs += pdf;
        fs += json["StudyUid"].toString() + ".json";
        emit reportSave(fs);
        emit reportModified(false);
        return true;
    }
    return false;
}

void ReportWidget::completeReport()
{
    ui->reportTimeEdit->setText(QDateTime::currentDateTime().toString(NORMAL_DATETIME_FORMAT));
    QJsonObject json = QJsonDocument::fromJson(report).object();
    json["Completed"] = true;
    report = QJsonDocument(json).toJson(QJsonDocument::Compact);
    saveReport();
    QJsonObject arg;
    arg["studyuid"] = json["StudyUid"].toString();
    arg["status"] = 41;
    m_status = 41;
    //emit postReport(QJsonDocument(arg).toJson(QJsonDocument::Compact));
    emit reportCompleted(true);
}

void ReportWidget::revokeComplete()
{
    ui->reportPhyCombo->setCurrentText("");
    ui->reportTimeEdit->clear();
    QJsonObject json = QJsonDocument::fromJson(report).object();
    json["Completed"] = false;
    report = QJsonDocument(json).toJson(QJsonDocument::Compact);
    saveReport();
    emit reportCompleted(false);
}

void ReportWidget::verifyReport()
{
    ui->verifySignLabel->setVisible(true);
    ui->verifyTimeEdit->setText(QDateTime::currentDateTime().toString(NORMAL_DATETIME_FORMAT));
    QJsonObject json = QJsonDocument::fromJson(report).object();
    json["Verified"] = true;
    report = QJsonDocument(json).toJson(QJsonDocument::Compact);
    printToPDF();
    saveReport();
    QJsonObject post;
    json = QJsonDocument::fromJson(report).object();
    post["studyuid"] = json["StudyUid"].toString();
    post["status"] = 5;
    m_status = 5;
    post["ftp_report_url"] = json["ReportPdf"].toString();
    emit postReport(QJsonDocument(post).toJson(QJsonDocument::Compact));
    emit reportVerified(true);
}

void ReportWidget::revokeVerify()
{
    //ui->verifyPhyCombo->setCurrentText("");
    ui->verifySignLabel->setVisible(false);
    ui->verifyTimeEdit->clear();
    QJsonObject json = QJsonDocument::fromJson(report).object();
    json["Verified"] = false;
    report = QJsonDocument(json).toJson(QJsonDocument::Compact);
    saveReport();
    emit reportVerified(false);
}

void ReportWidget::appendTemplateContents(const QString &findings, const QString &conclusion)
{
    // is verified?
    ui->findingsEdit->append(findings);
    ui->diagnoseEdit->append(conclusion);
}

void ReportWidget::loadImage(const QString &png)
{
    QJsonObject json = QJsonDocument::fromJson(report).object();
    QJsonArray arr = json["Images"].toArray();
    for (int i = 0; i < arr.size(); ++i) {
        QString name = arr[i].toString();
        if (png.right(name.size()) == name) {
            ImageLabel *l = 0;
            for (int i = 0; i < imgLabels.size(); ++i) {
                if (imgLabels.at(i)->getFileName() == name) {
                    l = imgLabels.at(i);
                    break;
                }
            }
            if (l) continue;
            l = insertImage(QPixmap(png), false);
            if (l) l->setFileName(name);
            break;
        }
    }
}

ImageLabel *ReportWidget::insertImage(const QPixmap &pixmap, bool modified)
{
    if (imgLabels.size() == 4) return 0;
    if (modified && (!ui->accNumEdit->isEnabled())) return 0;

    ImageLabel *l = new ImageLabel;
    ui->imageHBoxLayout->addWidget(l);
    imgLabels += l;
    l->setPixmap(pixmap);
    l->setContextMenuPolicy(Qt::ActionsContextMenu);
    QAction *a = new QAction(tr("Remove"), l);
    l->addAction(a);
    connect(a, SIGNAL(triggered(bool)), l, SLOT(deleteLater()));
    connect(a, SIGNAL(triggered(bool)), this, SLOT(onImageRemoved()));
    reflushReportFormat();

    QJsonObject json = QJsonDocument::fromJson(report).object();
    QString uid = json["StudyUid"].toString();
    l->setFileName(uid + "_" + QDateTime::currentDateTime().toString(DICOM_DATETIME_FORMAT) + ".png");

    if (modified) emit reportModified(true);
    return l;
}

void ReportWidget::onImageRemoved()
{
    imgLabels.removeOne(qobject_cast<ImageLabel*>(sender()->parent()));
    emit reportModified(true);
}

void ReportWidget::print()
{
    QPrinter printer;
    QPrintDialog dialog(&printer, this);
    if (dialog.exec() == QDialog::Accepted) {
        doPrint(&printer);
    }
}

void ReportWidget::printToPDF()
{
    QJsonObject json = QJsonDocument::fromJson(report).object();
    QString pdf = json["StudyUid"].toString() + "_" + QDateTime::currentDateTime().toString(DICOM_DATETIME_FORMAT) + ".pdf";
    json["ReportPdf"] = pdf;
    report = QJsonDocument(json).toJson(QJsonDocument::Compact);
    QPrinter p;
    p.setOutputFormat(QPrinter::PdfFormat);
    p.setOutputFileName(cacheDir + "/" + pdf);
    p.setPageSize(QPagedPaintDevice::A4);
    p.setResolution(1200);
    doPrint(&p);
    /*
    QUrl url(cacheDir + "/" + pdf);
    url.setScheme("file");
    QDesktopServices::openUrl(url);
    */
}

void ReportWidget::printPreview()
{
    QPrintPreviewDialog dialog(this);
    connect(&dialog, SIGNAL(paintRequested(QPrinter*)), this, SLOT(doPrint(QPrinter*)));
    dialog.setWindowFlags(dialog.windowFlags()|Qt::WindowMaximizeButtonHint);
    dialog.exec();
}

void ReportWidget::doPrint(QPrinter *printer)
{
    QSettings s;
    double left, top, right, bottom;
    left = s.value(PAGE_MARGIN_LEFT, LEFT_MARGIN_DEFAULT).toDouble();
    top = s.value(PAGE_MARGIN_TOP, TOP_MARGIN_DEFAULT).toDouble();
    right = s.value(PAGE_MARGIN_RIGHT, RIGHT_MARGIN_DEFAULT).toDouble();
    bottom = s.value(PAGE_MARGIN_BOTTOM, BOTTOM_MARGIN_DEFALT).toDouble();
    printer->setPageMargins(left, top, right, bottom, QPrinter::Millimeter);

    QPainter painter(printer);
    double mm2dot = printer->resolution()/(double)25.40;
    int BlockSpace = 3*mm2dot;

    QRect viewRect = painter.viewport();
    int totalHeight = 0;
    int height;

    painter.setFont(ui->institutionEdit->font());
    height = painter.fontMetrics().height();
    painter.drawText(QRect(0, totalHeight, viewRect.width(), height),
                     Qt::AlignCenter, ui->institutionEdit->text());
    totalHeight += height*1.4;

    painter.setFont(ui->reportTitleEdit->font());
    height = painter.fontMetrics().height();
    painter.drawText(QRect(0, totalHeight, viewRect.width(), height),
                     Qt::AlignCenter, ui->reportTitleEdit->text());
    totalHeight += height*1.4;
    totalHeight += BlockSpace*2;

    height = mm2dot;
    painter.drawLine(0, totalHeight+height/2, viewRect.width(), totalHeight+height/2);
    totalHeight += height;
    totalHeight += BlockSpace*2;

    painter.setFont(ui->patientNameLabel->font());
    height = painter.fontMetrics().height();
    painter.drawText(0, totalHeight, ui->patientNameLabel->text() + ui->patientNameEdit->text());
    painter.drawText(viewRect.width()/3, totalHeight,
                     ui->patientSexLabel->text() + ui->patientSexEdit->text());
    painter.drawText(viewRect.width()*2/3, totalHeight,
                     ui->accNumLabel->text() + ui->accNumEdit->text());
    totalHeight += height*1.5;
    //totalHeight -= BlockSpace*2;

    painter.setFont(ui->patientIdEdit->font());
    height = painter.fontMetrics().height();
    painter.drawText(0, totalHeight,
                     ui->patientIdLabel->text() + ui->patientIdEdit->text());
    painter.drawText(viewRect.width()/3, totalHeight,
                     ui->patientAgeLabel->text() + ui->patientAgeEdit->text());
    painter.drawText(viewRect.width()*2/3, totalHeight,
                     ui->studyTimeLabel->text() + ui->studyTimeEdit->text());
    totalHeight += height*1.5;
    //totalHeight += BlockSpace;

    painter.drawText(0, totalHeight,
                     ui->bodyPartLabel->text() + ui->bodyPartCombo->currentText());
    painter.drawText(viewRect.width()*2/3, totalHeight,
                     ui->studyMethodLabel->text() + ui->studyMethodEdit->text());

    totalHeight += height;
    //totalHeight -= BlockSpace*0.5;

    height = mm2dot;
    painter.drawLine(0, totalHeight+height/2, viewRect.width(), totalHeight+height/2);
    totalHeight += height;
    totalHeight += BlockSpace;

    if (imgLabels.size()) {
        QSettings settings;
        int imageWidth = settings.value(IMAGE_WIDTH).toDouble()*mm2dot;
        int imageHeight = settings.value(IMAGE_HEIGHT).toDouble()*mm2dot;
        int gridWidth = viewRect.width()/imgLabels.size();
        int height = 0;
        if (imageWidth > gridWidth) imageWidth = gridWidth;

        if (viewRect.height() - totalHeight < height) {
            printer->newPage();
            totalHeight = 0;
        }

        for (int i = 0; i < imgLabels.size(); ++i) {
            QPixmap pixmap = imgLabels[i]->pixmap().scaled(imageWidth, imageHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            height = height>pixmap.height()?height:pixmap.height();
            painter.drawPixmap(i*gridWidth + (gridWidth-pixmap.width())/2,
                               totalHeight, pixmap);
        }
        totalHeight += height;
        totalHeight += BlockSpace;
    }

    painter.setFont(ui->reportPhyLabel->font());
    int tailHeight = painter.fontMetrics().height()*5;
    //tailHeight += BlockSpace;
    painter.setFont(ui->footNoteEdit->font());
    tailHeight += painter.fontMetrics().height()*2;

    totalHeight += BlockSpace*2;
    painter.setFont(ui->findingsLabel->font());
    height = painter.fontMetrics().height();
    painter.drawText(0, totalHeight, ui->findingsLabel->text());
    totalHeight += height;

    int findingsHeight = (viewRect.height()-totalHeight-tailHeight-height*2)*2/3;
    painter.setFont(ui->findingsEdit->font());
    int indent = painter.fontMetrics().boundingRect(viewRect, Qt::AlignLeft, QString::fromUtf8("缩进")).width();
    height = painter.fontMetrics().boundingRect(QRect(0, 0, viewRect.width()-indent, viewRect.height()),
                                                Qt::AlignLeft|Qt::TextWordWrap,
                                                ui->findingsEdit->toPlainText()).height();

    height = height>findingsHeight?height:findingsHeight;
    painter.drawText(QRect(indent, totalHeight, viewRect.width()-indent, height),
                     Qt::AlignLeft|Qt::TextWordWrap,
                     ui->findingsEdit->toPlainText());
    totalHeight += height;

    painter.setFont(ui->diagnoseLabel->font());
    height = painter.fontMetrics().height();
    painter.drawText(0, totalHeight, ui->diagnoseLabel->text());
    totalHeight += height;

    painter.setFont(ui->diagnoseEdit->font());
    height = painter.fontMetrics().boundingRect(QRect(0, 0, viewRect.width()-indent, viewRect.height()),
                                                Qt::AlignLeft|Qt::TextWordWrap,
                                                ui->diagnoseEdit->toPlainText()).height();

    painter.drawText(QRect(indent, totalHeight, viewRect.width()-indent, height),
                     Qt::AlignLeft|Qt::TextWordWrap,
                     ui->diagnoseEdit->toPlainText());
    totalHeight += height;
    totalHeight += BlockSpace*2;

    totalHeight = viewRect.height() - tailHeight;
    painter.setFont(ui->reportPhyCombo->font());
    height = painter.fontMetrics().height();
    painter.drawText(viewRect.width()/3, totalHeight,
                     ui->reportPhyLabel->text() + "  " +ui->reportPhyCombo->currentText());
    painter.drawText(viewRect.width()*2/3, totalHeight,
                     ui->reportTimeLabel->text() + ui->reportTimeEdit->text());
    totalHeight += height*1.2;

    if (ui->verifySignLabel->isVisible()) {
        QPixmap sign = ui->verifySignLabel->pixmap()->scaledToHeight(height*3, Qt::SmoothTransformation);
        painter.drawText(viewRect.width()/3, totalHeight+height, ui->verifyPhyLabel->text());
        painter.drawPixmap(viewRect.width()/3+painter.fontMetrics().width(ui->verifyPhyLabel->text()), totalHeight-height, sign);
        totalHeight += height;
    } else {
        painter.drawText(viewRect.width()/3, totalHeight,
                         ui->verifyPhyLabel->text()/* + ui->verifyPhyCombo->currentText()*/);
    }

    painter.drawText(viewRect.width()*2/3, totalHeight,
                     ui->verifyTimeLabel->text() + ui->verifyTimeEdit->text());

    totalHeight += height*1.5;
    totalHeight -= BlockSpace;

    height = mm2dot;
    painter.drawLine(0, totalHeight+height/2, viewRect.width(), totalHeight+height/2);
    totalHeight += height;
    totalHeight += BlockSpace*2;

    painter.setFont(ui->footNoteEdit->font());
    height = painter.fontMetrics().height();
    painter.drawText(0, totalHeight, ui->footNoteEdit->text());

    /*
    QPixmap pixmap(rect().size());
    render(&pixmap);
    QPainter painter(printer);
    QRect viewRect = painter.viewport();
    QPixmap scaled = pixmap.scaled(viewRect.width(), viewRect.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    painter.drawPixmap((viewRect.width()-scaled.width())/2, 0, scaled);
    */
}

